<template>
  <page-header-wrapper :title="false">
    <a-card title="已开发票列表">
      <a-tabs v-model="tab" type="card" @change="onTab">
        <a-tab-pane key="40" tab="已审核未开票"></a-tab-pane>
        <a-tab-pane key="42" tab="已审核已开票"></a-tab-pane>
      </a-tabs>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="合同编号">
                <a-input type="text" v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="提交顾问">
                <a-select
                  show-search
                  v-model="queryParam['filter[adviser_uid]']"
                  placeholder="选择顾问姓名"
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="申请时间">
                <a-range-picker @change="onCreateAt" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="开票时间">
                  <a-range-picker @change="onCheckAt" />
                </a-form-item>
              </a-col>
              <a-col v-if="tab == 2" :md="6" :sm="24">
                <a-form-item label="是否完善">
                  <a-select
                    v-model="queryParam['filter[is_perfect]']"
                    placeholder="发票信息是否已完善"
                  >
                    <a-select-option :value="1">是</a-select-option>
                    <a-select-option :value="2">否</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
<!--              <a-col :md="6" :sm="24">-->
<!--                <a-form-item label="发票抬头">-->
<!--                  <a-input type="text" v-model="queryParam['filter[header]']" placeholder="输入开票抬头" />-->
<!--                </a-form-item>-->
<!--              </a-col>-->
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="table-operator">
        <s-table
          bordered
          ref="table"
          :row-key="(record) => record.id"
          :columns="invoiceColumns"
          :data="invoiceData"
        >
          <div slot="title">
            <a-button size="small" icon="export" type="primary" @click="exportInvoice">导出发票</a-button>
          </div>
          <template slot="contract_no" slot-scope="text,record">
            <a-button v-if="text == '合并合同'" type="link" @click="toDetail(record.id)">{{text}}</a-button>
            <a-button v-else type="link" @click="$router.push({ name: 'ContractDetail', params: { id: record.contract_id } })">{{text}}</a-button>
          </template>
          <template slot="company_name" slot-scope="text,record">
            {{text}}({{record.tax_point}}%)
          </template>
          <template slot="tm_name" slot-scope="text,record">
            {{text}}{{record.pt_name}}
          </template>
          <template slot="username" slot-scope="text, record">
            <a-tag>{{text}}</a-tag><br>
            <a-tag>{{record.group_type}}组</a-tag><br>
            <a-tag>{{record.leader_name}}</a-tag>
          </template>
          <template slot="file_url" slot-scope="text,record">
            <a-button
              v-if="record.file_url != ''"
              :title="record.filename"
              size="small"
              type="link"
              icon="download"
              @click="download(record.file_url)"
            >
              点击下载
            </a-button>
          </template>
          <template slot="action" slot-scope="text,record">
            <a-button v-if="record.info == 0 && tab == 42" size="small" type="danger" @click="uploadModal(record.id)" style="margin-right:5px">上传信息</a-button>
            <a-button v-if="record.info == 1 && tab == 42" size="small" disabled style="margin-right:5px">信息已完善</a-button>
            <a-button v-if="tab == 40" size="small" type="danger" @click="checkInvoice(record.id)">确认开票</a-button>
            <a-button size="small" type="primary" @click="toDetail(record.id)">详情</a-button>
          </template>
        </s-table>
      </div>
    </a-card>
    <a-modal
      title="审核发票"
      v-model="visible2"
      @ok="onSubmit"
      @cancel="onCancel"
    >
      <a-form-model>
        <a-form-model-item label="开票公司">
          <a-input type="text" v-model="invoiceForm.company_name" />
        </a-form-model-item>
        <a-form-model-item label="">
          <a-button size="small" type="link" icon="download" @click="download(invoiceForm.file_url)">{{invoiceForm.filename}}</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-radio-group v-model="invoiceForm.status">
            <a-radio v-for="(item,index) in statusOpts" :key="index" :value="index">{{item}}</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea disabled :rows="4" v-model="invoiceForm.notes"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="补充发票信息"
      v-model="visible"
      @ok="submitUpload"
    >
      <a-form-model
        ref="invoiceForm"
        :model="invoiceForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="发票编号" prop="invoice_num">
          <a-input type="text" v-model="invoiceForm.invoice_num" />
        </a-form-model-item>
        <a-form-model-item label="物流公司" prop="express_name">
          <a-input type="text" v-model="invoiceForm.express_name" />
        </a-form-model-item>
        <a-form-model-item label="物流单号" prop="express_num">
          <a-input type="text" v-model="invoiceForm.express_num" />
        </a-form-model-item>
        <a-form-model-item label="电子档发票">
          <a-upload
            name="file"
            :multiple="true"
            :action="uploadUrl"
            :headers="header"
            @change="handleChange"
          >
            <a-button> <a-icon type="upload" /> 上传电子档发票 </a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { STable } from '@/components'
import apis from '@/api'
import invoiceColumns from '@/columns/invoice'
import { getAddInfo, getCheck, getUnInvoice, postAddInfo, postCheck } from '@/api/invoice'

export default {
  components: {
    STable
  },
  name: 'InvoiceList',
  data () {
    return {
      tab: '40',
      invoiceColumns: invoiceColumns.invoiced,
      invoiceData: parameters => {
        return getUnInvoice(Object.assign(parameters, this.queryParam)).then(res => {
          this.adviserOpts = res.result.all_advisers
          return res.result
        })
      },
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      visible: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      invoiceRules: {
        invoice_num: [{ required: true, pattern: /(?!^\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{4,50}/, message: '必须填写正确的发票编号', trigger: 'blur' }],
        express_name: [{ required: true, pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, message: '必须填写正确的物流公司名称', trigger: 'blur' }],
        express_num: [{ required: true, pattern: /(?!^\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{4,50}/, message: '必须填写正确的物流单号', trigger: 'blur' }]
      },
      invoiceForm: {
        status: ''
      },
      queryParam: {},
      advanced: true,
      header: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      uploadUrl: apis.Upload,
      exportUrl: apis.ExportInvoice,
      adviserOpts: {},
      accessToken: storage.get(ACCESS_TOKEN),
      company: storage.get('company'),
      typeOpts: {},
      visible2: false,
      statusOpts: {}
    }
  },
  created () {
    this.queryParam['filter[status]'] = '40'
  },
  methods: {
    toDetail (id) {
      this.$router.push({ name: 'InvoiceDetail', params: { id } })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearch () {
      this.queryParam = {}
      this.queryParam['filter[created_at_start]'] = ''
      this.queryParam['filter[created_at_end]'] = ''
      this.queryParam['filter[check_time_start]'] = ''
      this.queryParam['filter[check_time_end]'] = ''
      this.$refs.table.refresh(true)
    },
    uploadModal (id) {
      const app = this
      app.invoiceForm = {}
      getAddInfo(id).then(res => {
        if (res.status === 0) {
          app.invoiceForm['invoice_id'] = id
          app.visible = true
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    download (url) {
      window.open(url)
    },
    submitUpload () {
      const app = this
      const data = {}
      app.$refs.invoiceForm.validate(valid => {
        if (valid) {
          for (const k in app.invoiceForm) {
            data['invoiceInfos[' + k + ']'] = app.invoiceForm[k]
          }
          postAddInfo(data, app.invoiceForm.invoice_id).then(res => {
            if (res.status === 0) {
              app.visible = false
              app.invoiceForm = {}
              app.$refs.table.refresh(true)
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        } else {
          return false
        }
      })
    },
    handleChange (info) {
      if (info.file.status === 'done') {
        this.invoiceForm['voice_electronic_file'] = info.file.response.result.url
      }
    },
    onCreateAt (date, dateString) {
      this.queryParam['filter[created_at_start]'] = dateString[0]
      this.queryParam['filter[created_at_end]'] = dateString[1]
    },
    onCheckAt (date, dateString) {
      this.queryParam['filter[check_time_start]'] = dateString[0]
      this.queryParam['filter[check_time_end]'] = dateString[1]
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    exportInvoice () {
      let params = this.exportUrl + '?access_token=' + this.accessToken + '&company=' + this.company
      for (const k in this.queryParam) {
        params = params + '&' + k + '=' + this.queryParam[k]
      }
      window.open(process.env.VUE_APP_API_BASE_URL + params)
    },
    getInvoice (id) {
      const app = this
      app.invoiceForm = {}
      getCheck(id).then(res => {
        const invoice = res.result.invoiceData
        app.typeOpts = res.result.invoice_type_opts
        for (const k in invoice) {
          app.invoiceForm[k] = invoice[k]
        }
      }).finally(() => {
        app.visible2 = true
      })
    },
    onTab (key) {
      this.queryParam['filter[status]'] = key
      this.$refs.table.refresh(true)
    },
    checkInvoice (id) {
      getCheck(id).then(res => {
        this.invoiceForm = res.result.invoiceData
        this.invoiceForm['invoice_id'] = id
        this.statusOpts = res.result.status2_items
        this.visible2 = true
      })
    },
    onSubmit () {
      const data = {}
      for (const k in this.invoiceForm) {
        data['invoice[' + k + ']'] = this.invoiceForm[k]
      }
      data['invoice_id'] = this.invoiceForm.invoice_id
      postCheck(data).then(res => {
        if (res.status === 0) {
          this.visible2 = false
          this.$refs.table.refresh(true)
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onCancel () {
    }
  }
}
</script>

<style scoped>

</style>
